//*********************************************************************
//		Copyright (c) 2003 - 2008 Microsoft Corporation.
//      This code is provided under Microsoft Public License, which can be found at
//      http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx 
//
// @File: FormW5.cs
//
// Purpose: Installation & Configuration Wizard - screen 5 (Configuration - Scheduling task)
//
//
//
// Notes: 
//
//
//	
// History: 
//     @Version: V2.1
//
//     08/18/08 PGV 2.1.001.0 Starting V2.1 (based on 2.0.030.0 code)
//
// @EndHeader@
//*********************************************************************

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace H2V2.ConfigUtility
{
	public class FormW5 : H2V2.ConfigUtility.FormWbase
	{
		int m_Run = 0;
		string m_Path;
		bool m_Disabled = false;

		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.DateTimePicker TimePicker;
		private System.Windows.Forms.TextBox tbPwd2;
		private System.Windows.Forms.TextBox tbPwd;
		private System.Windows.Forms.TextBox tbUser;
		private System.Windows.Forms.CheckBox cbSun;
		private System.Windows.Forms.CheckBox cbSat;
		private System.Windows.Forms.CheckBox cbFri;
		private System.Windows.Forms.CheckBox cbThu;
		private System.Windows.Forms.CheckBox cbWed;
		private System.Windows.Forms.CheckBox cbTue;
		private System.Windows.Forms.CheckBox cbMon;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.TextBox textBox2;
		private System.ComponentModel.IContainer components = null;

		public FormW5()
		{
			// This call is required by the Windows Form Designer.
			InitializeComponent();

			m_Path = ((MainForm.WizardMode) ? MainForm.BinPath : Environment.CurrentDirectory)
				+"\\SQLH2.exe";
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.TimePicker = new System.Windows.Forms.DateTimePicker();
			this.tbPwd2 = new System.Windows.Forms.TextBox();
			this.tbPwd = new System.Windows.Forms.TextBox();
			this.tbUser = new System.Windows.Forms.TextBox();
			this.cbSun = new System.Windows.Forms.CheckBox();
			this.cbSat = new System.Windows.Forms.CheckBox();
			this.cbFri = new System.Windows.Forms.CheckBox();
			this.cbThu = new System.Windows.Forms.CheckBox();
			this.cbWed = new System.Windows.Forms.CheckBox();
			this.cbTue = new System.Windows.Forms.CheckBox();
			this.cbMon = new System.Windows.Forms.CheckBox();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.label3 = new System.Windows.Forms.Label();
			this.textBox2 = new System.Windows.Forms.TextBox();
			this.panel1.SuspendLayout();
			this.SuspendLayout();
			// 
			// panel1
			// 
			this.panel1.Controls.Add(this.textBox2);
			this.panel1.Controls.Add(this.textBox1);
			this.panel1.Name = "panel1";
			// 
			// panel2
			// 
			this.panel2.Name = "panel2";
			// 
			// btCancel
			// 
			this.btCancel.Name = "btCancel";
			// 
			// btNext
			// 
			this.btNext.Name = "btNext";
			// 
			// textBox1
			// 
			this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
			this.textBox1.Font = new System.Drawing.Font("Arial", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204)));
			this.textBox1.Location = new System.Drawing.Point(24, 8);
			this.textBox1.Multiline = true;
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(496, 32);
			this.textBox1.TabIndex = 1;
			this.textBox1.TabStop = false;
			this.textBox1.Text = "Schedule a task for SQLH2 Collector";
			// 
			// TimePicker
			// 
			this.TimePicker.Format = System.Windows.Forms.DateTimePickerFormat.Time;
			this.TimePicker.Location = new System.Drawing.Point(56, 160);
			this.TimePicker.Name = "TimePicker";
			this.TimePicker.ShowUpDown = true;
			this.TimePicker.Size = new System.Drawing.Size(112, 20);
			this.TimePicker.TabIndex = 34;
			this.TimePicker.Value = new System.DateTime(2004, 6, 10, 3, 0, 0, 0);
			// 
			// tbPwd2
			// 
			this.tbPwd2.Location = new System.Drawing.Point(384, 312);
			this.tbPwd2.Name = "tbPwd2";
			this.tbPwd2.PasswordChar = '*';
			this.tbPwd2.Size = new System.Drawing.Size(200, 20);
			this.tbPwd2.TabIndex = 33;
			this.tbPwd2.Text = "";
			// 
			// tbPwd
			// 
			this.tbPwd.Location = new System.Drawing.Point(384, 264);
			this.tbPwd.Name = "tbPwd";
			this.tbPwd.PasswordChar = '*';
			this.tbPwd.Size = new System.Drawing.Size(200, 20);
			this.tbPwd.TabIndex = 32;
			this.tbPwd.Text = "";
			// 
			// tbUser
			// 
			this.tbUser.Location = new System.Drawing.Point(384, 216);
			this.tbUser.Name = "tbUser";
			this.tbUser.Size = new System.Drawing.Size(200, 20);
			this.tbUser.TabIndex = 31;
			this.tbUser.Text = "";
			// 
			// cbSun
			// 
			this.cbSun.Location = new System.Drawing.Point(192, 296);
			this.cbSun.Name = "cbSun";
			this.cbSun.TabIndex = 30;
			this.cbSun.Text = "Sunday";
			// 
			// cbSat
			// 
			this.cbSat.Location = new System.Drawing.Point(192, 256);
			this.cbSat.Name = "cbSat";
			this.cbSat.TabIndex = 29;
			this.cbSat.Text = "Saturday";
			// 
			// cbFri
			// 
			this.cbFri.Location = new System.Drawing.Point(192, 216);
			this.cbFri.Name = "cbFri";
			this.cbFri.TabIndex = 28;
			this.cbFri.Text = "Friday";
			// 
			// cbThu
			// 
			this.cbThu.Checked = true;
			this.cbThu.CheckState = System.Windows.Forms.CheckState.Checked;
			this.cbThu.Location = new System.Drawing.Point(56, 336);
			this.cbThu.Name = "cbThu";
			this.cbThu.TabIndex = 27;
			this.cbThu.Text = "Thursday";
			// 
			// cbWed
			// 
			this.cbWed.Location = new System.Drawing.Point(56, 296);
			this.cbWed.Name = "cbWed";
			this.cbWed.TabIndex = 26;
			this.cbWed.Text = "Wednesday";
			// 
			// cbTue
			// 
			this.cbTue.Location = new System.Drawing.Point(56, 256);
			this.cbTue.Name = "cbTue";
			this.cbTue.TabIndex = 25;
			this.cbTue.Text = "Tuesday";
			// 
			// cbMon
			// 
			this.cbMon.Checked = true;
			this.cbMon.CheckState = System.Windows.Forms.CheckState.Checked;
			this.cbMon.Location = new System.Drawing.Point(56, 216);
			this.cbMon.Name = "cbMon";
			this.cbMon.TabIndex = 24;
			this.cbMon.Text = "Monday";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(376, 192);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(128, 23);
			this.label1.TabIndex = 35;
			this.label1.Text = "Account (Domain\\user):";
			this.label1.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(376, 240);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(128, 23);
			this.label2.TabIndex = 36;
			this.label2.Text = "Password:";
			this.label2.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(376, 288);
			this.label3.Name = "label3";
			this.label3.TabIndex = 2;
			this.label3.Text = "Confirm Password:";
			this.label3.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
			// 
			// textBox2
			// 
			this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
			this.textBox2.Font = new System.Drawing.Font("Arial", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204)));
			this.textBox2.Location = new System.Drawing.Point(40, 40);
			this.textBox2.Multiline = true;
			this.textBox2.Name = "textBox2";
			this.textBox2.Size = new System.Drawing.Size(560, 64);
			this.textBox2.TabIndex = 2;
			this.textBox2.TabStop = false;
			this.textBox2.Text = "Wizard creates task named SQLH2_Collector.\r\nThe task can be changed (created, del" +
				"eted) using Control Panel Scheduled Tasks.";
			// 
			// FormW5
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(640, 478);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.TimePicker);
			this.Controls.Add(this.tbPwd2);
			this.Controls.Add(this.tbPwd);
			this.Controls.Add(this.tbUser);
			this.Controls.Add(this.cbSun);
			this.Controls.Add(this.cbSat);
			this.Controls.Add(this.cbFri);
			this.Controls.Add(this.cbThu);
			this.Controls.Add(this.cbWed);
			this.Controls.Add(this.cbTue);
			this.Controls.Add(this.cbMon);
			this.Name = "FormW5";
			this.Activated += new System.EventHandler(this.ValidateWrapper);
			this.Controls.SetChildIndex(this.panel1, 0);
			this.Controls.SetChildIndex(this.panel2, 0);
			this.Controls.SetChildIndex(this.cbMon, 0);
			this.Controls.SetChildIndex(this.cbTue, 0);
			this.Controls.SetChildIndex(this.cbWed, 0);
			this.Controls.SetChildIndex(this.cbThu, 0);
			this.Controls.SetChildIndex(this.cbFri, 0);
			this.Controls.SetChildIndex(this.cbSat, 0);
			this.Controls.SetChildIndex(this.cbSun, 0);
			this.Controls.SetChildIndex(this.tbUser, 0);
			this.Controls.SetChildIndex(this.tbPwd, 0);
			this.Controls.SetChildIndex(this.tbPwd2, 0);
			this.Controls.SetChildIndex(this.TimePicker, 0);
			this.Controls.SetChildIndex(this.label1, 0);
			this.Controls.SetChildIndex(this.label2, 0);
			this.Controls.SetChildIndex(this.label3, 0);
			this.panel1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		void ValidateWrapper (object sender, System.EventArgs e)
		{
			if (m_Run == 0)
			{
				m_Run++;

				Thread RunThread = new Thread (new ThreadStart (this.ValidateEnvironment));
				RunThread.Start ();
			}
		}

		void ValidateEnvironment ()
		{
			System.OperatingSystem OS = Environment.OSVersion;
			string sOS = OS.ToString ();

			if (OS.Version.Major < 5 || (OS.Version.Major == 5 && OS.Version.Minor == 0))
			{
				DisableControls ();
				MessageBox.Show (this, "Wizard is able to schedule a task on Windows XP, Windows 2003 or higher platform only \r\n"
					+"Please configure task manually using Control Panel Scheduled Taks. (Program to run - sqlh2.exe)",
					"Validating environment", MessageBoxButtons.OK);
				return;
			}

			if (TaskExists ())
			{
				DisableControls ();
				MessageBox.Show (this, "SQLH2_Collector task already exists!",
					"Validating environment", MessageBoxButtons.OK);
				return;
			}

			if (!System.IO.File.Exists (m_Path))
			{
				DisableControls ();
				MessageBox.Show (this, "Wizard cannot locate SQLH2.exe \r\nA task cannot be scheduled",
					"Validating environment", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		void DisableControls ()
		{
			cbMon.Enabled = false;
			cbTue.Enabled = false;
			cbWed.Enabled = false;
			cbThu.Enabled = false;
			cbFri.Enabled = false;
			cbSat.Enabled = false;
			cbSun.Enabled = false;
			TimePicker.Enabled = false;
			tbUser.Enabled = false;
			tbPwd.Enabled = false;
			tbPwd2.Enabled = false;

			m_Disabled = true;
		}

		bool ValidatePassword ()
		{
			if (tbUser.Text == "")
			{
				MessageBox.Show ("User name is not supplied", "Scheduling Task", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			if (tbPwd.Text == "" || tbPwd.Text != tbPwd2.Text)
			{
				MessageBox.Show ("Supplied passwords don't match", "Scheduling Task", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			return true;
		}

		string GenerateCommand ()
		{
			string cmd, 
				d = "",
				dt;
			int q = 0;

			#region Forming Days string
			if (cbMon.Checked)
			{
				d = "MON";
				q++;
			}
			if (cbTue.Checked)
			{
				if (q > 0) d += ",";
				d += "TUE";
				q++;
			}
			if (cbWed.Checked)
			{
				if (q > 0) d += ",";
				d += "WED";
				q++;
			}
			if (cbThu.Checked)
			{
				if (q > 0) d += ",";
				d += "THU";
				q++;
			}
			if (cbFri.Checked)
			{
				if (q > 0) d += ",";
				d += "FRI";
				q++;
			}
			if (cbSat.Checked)
			{
				if (q > 0) d += ",";
				d += "SAT";
				q++;
			}
			if (cbSun.Checked)
			{
				if (q > 0) d += ",";
				d += "SUN";
				q++;
			}
			#endregion

			dt = TimePicker.Value.ToString ("hh:mm:ss");

			cmd = "/Create /RU "+tbUser.Text+" /RP "+tbPwd.Text+" /SC WEEKLY /D "+d
				+" /ST "+dt+" /TN SQLH2_Collector /TR "+m_Path;

			return cmd;
		}

		bool ScheduleTask ()
		{
			string args,
				output;
			int ExitCode;
			bool ret = true;
				
			args = GenerateCommand ();

			try
			{
				Process p=new Process ();
				p.StartInfo.FileName = "schtasks.exe";
				p.StartInfo.CreateNoWindow = true;
				p.StartInfo.UseShellExecute = false;
				p.StartInfo.RedirectStandardOutput = true;
				p.StartInfo.Arguments = args;

				p.Start ();
				output = p.StandardOutput.ReadToEnd();
				p.WaitForExit();
				ExitCode = p.ExitCode;
				p.Close ();

				if (ExitCode != 0)
				{
					DialogResult dr = MessageBox.Show ("Task creation failed!\r\n"
						+"Please configure task manually using Control Panel Scheduled Taks. (Program to run - sqlh2.exe)",
						"Scheduling task", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				else if (output.StartsWith ("WARNING"))
				{
					DialogResult dr = MessageBox.Show ("The following warning was received while scheduling task: \r\n"+output
						+"Would you like to correct supplied informaition and try again?", "Scheduling task", MessageBoxButtons.YesNoCancel);

					if (dr != DialogResult.No)
					{
						DeleteTask ();
						ret = false;
					}
				}
				else if (output.StartsWith ("ERROR"))
				{
					DialogResult dr = MessageBox.Show ("The following error was received while scheduling task: \r\n"+output
						+"Would you like to correct supplied informaition and try again?", "Scheduling task", MessageBoxButtons.YesNoCancel);
					if (dr != DialogResult.Yes)
					{
						ret = false;
					}
				}
			}
			catch 
			{
				DialogResult dr = MessageBox.Show ("Task creation failed!\r\n"
					+"Please configure task manually using Control Panel Scheduled Taks. (Program to run - sqlh2.exe)",
					"Scheduling task", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return ret;
		}

		void DeleteTask ()
		{
			Process p=new Process ();
			p.StartInfo.FileName = "schtasks.exe";
			p.StartInfo.CreateNoWindow = true;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.Arguments = "/Delete /TN SQLH2_Collector /F";

			p.Start ();
			string output = p.StandardOutput.ReadToEnd();
			p.WaitForExit();
			int ExitCode = p.ExitCode;
			p.Close ();
		}

		bool TaskExists ()
		{
			string output,
				s;
			int ExitCode;

			Process p=new Process ();
			p.StartInfo.FileName = "schtasks.exe";
			p.StartInfo.CreateNoWindow = true;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.Arguments = "/Query /NH ";

			p.Start ();
			output = p.StandardOutput.ReadToEnd();
			p.WaitForExit();
			ExitCode = p.ExitCode;
			p.Close ();

			StringReader sr = new StringReader (output);
			while ((s = sr.ReadLine ()) != null)
			{
				if (s.StartsWith ("SQLH2_Collector"))
				{
					return true;
				}
			}

			return false;
		}

		protected override void btNext_Click(object sender, System.EventArgs e)
		{
			if (!m_Disabled)
			{
				if (ValidatePassword ())
				{
					if (!ScheduleTask ())
					{
						return;
					}
				}
				else 
				{
					return;
				}
			}

			base.btNext_Click (sender, e);
		}

		protected override void btCancel_Click(object sender, System.EventArgs e)
		{
			if (!m_Disabled)
			{
				DialogResult dr = MessageBox.Show ("Quitting at this point will leave SQLH2 configured,"
					+"but it will not be scheduled to run! \r\n"
					+"Do you want to quit?", "Scheduling Task", MessageBoxButtons.YesNoCancel);
				if (dr != DialogResult.Yes)
				{
					return;
				}
			}

			base.btCancel_Click (sender, e);
		}

	}
}

